package com.example.securitytest.api;

import com.example.securitytest.dao.MyUserDAO;
import com.example.securitytest.dataobject.MyUser;
import com.example.securitytest.model.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api/user")
public class UserAPI {

	@Autowired
	private MyUserDAO myUserDAO;

	/**
	 * 判断用户登录，这个api会被加入Spring Security拦截器，若用户没有登录会返回无权访问403
	 *
	 * @return 用户信息
	 */
	@GetMapping("/islogin")
	public Result<MyUser> isLogin(Authentication authentication) { // 在Controller类方法中加上Spring Security的Authentication类型参数，可以获取当前登录的用户信息例如用户名等等
		Result<MyUser> result = new Result<>();
		// 判断是否登录，如果未登录通常这个authentication为null
		if (authentication == null || !authentication.isAuthenticated()) {
			result.setResultFailed("用户未登录！");
			return result;
		}
		// 获取当前登录的用户信息
		UserDetails userDetails = (UserDetails) authentication.getPrincipal();
		// 获取用户名并查询用户
		MyUser myUser = myUserDAO.getByUsername(userDetails.getUsername());
		if (myUser == null) {
			result.setResultFailed("用户无效！");
			return result;
		}
		result.setResultSuccess("用户已经登录！", myUser);
		return result;
	}

}